import { createApp, ComponentPublicInstance, Component } from 'vue'
import { MakeLayerMountComponent, updateElementStyle } from './MountComponent'

// 动态添加挂件
export const useLoadWidget = (eleDiv: Element) => {

    let _div: Element | null = null
    let _instance: ComponentPublicInstance = null

    // 初始化挂件
    const initialLoadWidget = (data: object) => {

        let eleStyle: ElementStyle | null = null;
        // 如果已经有挂架存在，则删除之前的挂件
        if (_instance && _div) {
            eleStyle = getElementStyle((_div as HTMLElement));
            uninitialWidget();
        }

        let { div, instance } = MakeLayerMountComponent(eleDiv, {
            ...data,
            onclose: () => {
                _instance.unmount()
                _div?.remove()
                _div = null;
            }
        })

        // 如果有上一个元素，则使用上一个元素的位置
        eleStyle && eleStyle.updateStyle(div)

        _instance = instance;
        _div = div;

        return { div, instance }
    }

    // 卸载挂件
    const uninitialWidget = () => {
        if (_instance) {
            _instance.unmount()
            _div?.remove()
            _div = null;
        }
    }

    return {
        initialLoadWidget,
        uninitialWidget
    }
}

interface ElementStyle {
    updateStyle: Function
}
// 获取上一个元素的位置，并用在新元素上，类似实现无感刷新
const getElementStyle = (_div: HTMLElement): ElementStyle => {

    let { left, top, width, height } = (_div?.firstChild as HTMLElement).getBoundingClientRect();

    const updateStyle = (div: HTMLElement) => {

        if (!div) return false;

        // 初始化元素的位置
        updateElementStyle(div, { left, top, width, height })

    }

    return {
        updateStyle
    }
}
